package com.py.custom.business.demo.feign.channel;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.py.custom.business.demo.protocol.constants.Constants;
import com.py.custom.business.demo.protocol.dto.MessageTaskDTO;
import com.py.custom.business.demo.protocol.dto.SendResultDTO;
import com.py.custom.common.web.utils.RestTemplateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * description：钉钉渠道发送
 */
@Component
@Slf4j
public class DingDingChannel implements Channel {

    @Resource
    private RestTemplateUtils restTemplateUtils;

    private String url = "https://oapi.dingtalk.com/robot/send?access_token=32354a04e5ea8bf91cbe78a584384b4b008192fb27d1f28330dfa0f0b431f359";

    @Override
    public SendResultDTO doSendMessage(MessageTaskDTO messageTaskDto) {
        log.info("DingDingChannel send message：" + messageTaskDto.getMessage());
        SendResultDTO sendResultDTO = new SendResultDTO();
        try {
            JSONObject params = new JSONObject();
            params.put("msgtype", "text");
            JSONObject contentParam = new JSONObject();
            contentParam.put("content", messageTaskDto.getMessage());
            params.put("text", contentParam);
            ResponseEntity<String> response = restTemplateUtils.postByJson(url, params.toJSONString(), String.class);
            if (HttpStatus.OK == response.getStatusCode()) {
                String body = response.getBody();
                JSONObject parseObject = JSON.parseObject(body);
                Integer code = parseObject.getInteger(Constants.ERROR_CODE);
                if (code != null && Constants.CODE_NUB == code) {
                    sendResultDTO.setCode(Constants.CODE_NUB);

                } else {
                    String msg = parseObject.getString(Constants.ERROR_MSG);
                    sendResultDTO.setCode(Constants.CODE_FAIL);
                    sendResultDTO.setMsg(msg);
                }
            }
        } catch (Exception ex) {
            // 上报服务错误
            sendResultDTO.setCode(Constants.CODE_ERR);
        }
        return sendResultDTO;
    }
}
